package com.open.ssm.common.aspectj;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 记录设备变更历史切面处理
 * 
 * 执行顺序：around->before->jointPoint.proceed()->around->after->afterReturing
 * @Before: 前置通知，在方法执行之前执行
 * @Around: 环绕通知，围绕着方法执行
 * @After: 后置通知，在方法执行之后执行 。
 * @AfterReturing: 返回通知，在方法返回结果之后执行
 *
 * @version: v1.0.0
 * @author: wangpf
 * @date: 2022年6月24日 下午4:12:39
 */
@Aspect
@Component
public class ModiLogAspect {
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	/*@Autowired
    private IAmsAsModiHisService amsAsModiHisService;*/
	
    @PostConstruct
    public void init() {
    }

    @Pointcut(value = "@annotation(com.open.ssm.common.annotation.ModiLog)")
    public void annotationPointCut() {
    }
    
    /**
     * 环绕增强，相当于MethodInterceptor
     */
    @Around("annotationPointCut()")
    public Object doAround(ProceedingJoinPoint joinPoint) {
    	logger.info("---@Around---");
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        // 编辑edit，新增add
        String methodName = signature.getMethod().getName();
        String className = joinPoint.getTarget().getClass().getSimpleName();
        
        /*if("edit".equals(methodName)) {// 更新操作日志
        	//通过joinPoint.getArgs()获取Args参数
            Object[] args = joinPoint.getArgs();
            for(Object object : args) {
            	if(!(object instanceof BaseEntity)) {
            		continue;
            	}
            	
            	// 记录资产变更信息
            	if(object instanceof Station) {
            		Station newEntity = (Station)object;
            		insertStationModiHis(className, methodName, newEntity);
            	}else if(object instanceof Stake) {
            		Stake newEntity = (Stake)object;
            		insertStakeModiHis(className, methodName, newEntity);
            	}
            } // end for(Object object : args)
        }else if("remove".equals(methodName)) {// 删除操作日志
        	//通过joinPoint.getArgs()获取Args参数
            Object[] args = joinPoint.getArgs();
            for(Object object : args) {
            	if(object.getClass().isArray()) {
            		String[] ids = (String[])object;
            		// 保存变更内容
            		AmsAsModiHis amsAsModiHis = new AmsAsModiHis();
            		if(ids.length > 0) {
            			switch(className) {
	            			case "AmsAsStationController":
	            				amsAsModiHis.setAssetId(ids[0]);
	            				Station station = stationService.selectAmsAsStationById(ids[0]);
	            				if(station != null) {
	            					amsAsModiHis.setAssetCode(station.getStationNo());
	            					amsAsModiHis.setAssetType("");
	            				}
	            				amsAsModiHis.setMethodName("资产:删除");
	            				break;
            			}
            		}
            		amsAsModiHis.setModiContent(Arrays.toString(ids));
            		amsAsModiHis.setModiResult("");
            		amsAsModiHis.setClassName(className+":"+methodName);
            		amsAsModiHis.setRemark("资产删除");
            		amsAsModiHisService.insertAmsAsModiHis(amsAsModiHis);
            	}
            }
        }*/

        try {
            return joinPoint.proceed();
        } catch (Throwable throwable) {
            return null;
        }
    }
    
    @Before("annotationPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
    	logger.info("---@Before---");
    }
    
    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     * @param jsonResult 返回值
     */
    @AfterReturning(pointcut = "annotationPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
    	logger.info("---@AfterReturning---jsonResult={}", jsonResult);
    }

    /**
     * 拦截异常操作
     * 
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "annotationPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
    	logger.info("---@AfterThrowing---");
    }
    
}
